#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>
#include "uFire_SHT20.h"
#include <NTPClient.h>
#include <WiFiUdp.h>
#include "Ticker.h"
#include <ArduinoJson.h>


WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "asia.pool.ntp.org");
uFire_SHT20 sht20;

void send_message();
Ticker timer1(send_message,5000);
WiFiClient espClient;
PubSubClient client(espClient);
StaticJsonDocument<100> doc;
const char* ssid = "MERCURY_D6FE";//连接的路由器的名字
const char* password = "999999999";//连接的路由器的密码
const char* mqtt_server = "182.92.65.55";//服务器的地址 
const int port=1883;//服务器端口号
  
const char*  pub_name = "humiture/c";
uint8_t MAC_array_STA[6];
char MAC_char_STA[18];




 //初始化WIFI
void setup_wifi() {//自动连WIFI接入网络
    delay(10);

    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print("...");
    }
}

void reconnect() {//等待，直到连接上服务器
    while (!client.connected()) {//如果没有连接上
      if (client.connect(MAC_char_STA)) {//接入时的用户名，尽量取一个很不常用的用户名
        client.subscribe(pub_name);//接收外来的数据时的intopic
        Serial.println("connect success");
      } else {
        Serial.print("failed, rc=");//连接失败
        Serial.print(client.state());//重新连接
        Serial.println(" try again in 5 seconds");//延时5秒后重新连接
        delay(5000);
      }
    }
}

/*mqtt接受消息回调函数*/
void callback(char* topic, byte* payload, unsigned int length) {

}                             

void setup() {
  Serial.begin(9600);     //串口初始化   
  setup_wifi();           //wifi初始化

  WiFi.macAddress(MAC_array_STA);
  for (int i = 0; i < 6; ++i) {
    sprintf(MAC_char_STA, "%s%02x", MAC_char_STA, MAC_array_STA[i]);
  }
  Serial.println(MAC_char_STA);
  timeClient.begin();     //ntp初始化
  timer1.start();         //定时器初始化

  //mqtt初始化
  client.setServer(mqtt_server, port);
  client.setCallback(callback); 
  client.connect(MAC_char_STA);
}

void loop() {
  client.loop();
  timer1.update();
  timeClient.update();
}

void send_message(){

  StaticJsonDocument<100> doc;
  reconnect();//确保连上服务器，否则一直等待。
  doc["device_sn"] = MAC_char_STA;
  doc["temp"] = (String)sht20.temperature();
  doc["humidity"] =(String)sht20.humidity();
  doc["time"] = (String)timeClient.getEpochTime();
  String pub_content;
  serializeJson(doc, pub_content);
  if(!client.publish(pub_name,pub_content.c_str())){
     Serial.println("publish error!");
  }
  Serial.println(pub_content);
}